<!--记账页面-->
<template>
  <!-- <div v-loading="pageLoading"> -->
  <div v-loading="loading">
    <!-- 表单区域 -->
    <el-card>
      <el-form
        :model="searchCriteria"
        :inline="true"
        :rules="rules"
        ref="searchCriteria"
        size="mini"
        class="padding-top-sm flex justify-between"
        label-width="auto"
      >
        <el-form-item prop="accountNo" label="记账编号">
          <!-- <el-input v-model="searchCriteria.accountNo" clearable /> -->
          <el-popover
            placement="right"
            width="260"
            trigger="click"
            v-model="accountNoVisible"
          >
            <div class="flex align-center">
              <el-input v-model="accountNo" class="margin-right" />
              <i
                class="el-icon-success text-xxl text-green"
                @click="saveAccountNo"
              ></i>
              <i class="el-icon-error text-xxl text-red" @click="closePop"></i>
            </div>
            <span slot="reference">{{ searchCriteria.accountNo }}</span>
          </el-popover>
        </el-form-item>
        <el-form-item prop="accountTime" label="记账日期">
          <el-date-picker
            v-model="searchCriteria.accountTime"
            value-format="yyyy-MM-dd"
            @change="accountTimeChange"
          />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input
            v-model="searchCriteria.remark"
            style="width:500px"
            clearable
          />
        </el-form-item>
        <el-form-item prop="publicOpen" label="是否公开">
          <el-radio v-model="searchCriteria.publicOpen" label="1">是</el-radio>
          <el-radio v-model="searchCriteria.publicOpen" label="0">否</el-radio>
        </el-form-item>
        <el-alert
          :title="'数据同步剩余数: ' + mqCount"
          :closable="false"
          style="height: 30px; width: 200px"
          show-icon
          type="warning"
          v-if="mqCount > 0"
        >
        </el-alert>
        <el-button
          size="mini"
          type="success"
          @click="save()"
          :disabled="mqCount > 0"
          >保存</el-button
        >
      </el-form>
    </el-card>
    <!-- 表单区域 -->
    <el-card class="margin-top">
      <el-form
        :model="searchCriteria"
        :inline="true"
        size="mini"
        :rules="rules"
        ref="searchCriteria"
        class="padding-top-sm"
        label-position="left"
        label-width="90px"
      >
        <el-row :gutter="10">
          <el-col :span="6">
            <!--新增操作-->
            <el-form-item
              prop="serCusId"
              v-if="financeAccount === null"
              label="公司简称"
            >
              <el-select
                style="width:220px"
                v-model="searchCriteria.serCusId"
                :remote-method="autoComplete"
                placeholder="请输入至少两个关键字"
                clearable
                filterable
                remote
                @change="selectCustomerOrService"
              >
                <el-option-group
                  v-for="(v, i) in serCusIdMap"
                  :key="i"
                  :label="m(v.text)"
                >
                  <el-option
                    v-for="(val, index) in v.children"
                    :key="index"
                    :label="val.text"
                    :value="val.id"
                  ></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
            <!--编辑禁止客户或者服务商编辑-->
            <el-form-item prop="serCusId" v-else label="公司简称">
              <el-select
                style="width:220px"
                v-model="searchCriteria.serCusId"
                clearable
                filterable
                disabled
              >
                <el-option
                  v-for="(v, i) in editCustomerOrServiceMap"
                  :key="i"
                  :label="v"
                  :value="i"
                ></el-option>
              </el-select>
              <!--              {{searchCriteria.serCusId}}-->
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="searchCriteria.relatedSon"
                >关联子公司</el-checkbox
              >
            </el-form-item>
            <el-form-item prop="inputUser" label="录入人">
              <el-select
                v-model="searchCriteria.inputUser"
                filterable
                clearable
                style="width:220px"
                ><el-option
                  v-for="(v, i) in userSource"
                  :key="i"
                  :label="v"
                  :value="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="receivePaymentReamrk" label="应收应付备注">
              <el-select
                style="width:220px"
                v-model="searchCriteria.receivePaymentReamrk"
                :remote-method="queryReceiveReamrk"
                placeholder="请输入"
                clearable
                filterable
                remote
              >
                <el-option
                  v-for="(v, i) in remarkMap"
                  :key="i"
                  :label="v"
                  :value="v"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="costNames" label="费用名称">
              <el-select
                style="width:220px"
                v-model="searchCriteria.costNames"
                filterable
                multiple
                clearable
              >
                <el-option
                  v-for="(v, i) in costNamesMap"
                  :key="i"
                  :label="v"
                  :value="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="accountDate" label="费用时间">
              <el-date-picker
                v-model="searchCriteria.accountDate"
                unlink-panels
                type="daterange"
                style="width:220px"
                start-placeholde="开始时间"
                end-placeholde="结算时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item prop="inStockDate" label="入库时间">
              <el-date-picker
                v-model="searchCriteria.inStockDate"
                unlink-panels
                type="datetimerange"
                style="width:220px"
                start-placeholde="开始时间"
                end-placeholde="结算时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
            <el-form-item prop="saleId" label="销售">
              <el-select
                style="width:220px"
                v-model="searchCriteria.saleId"
                filterable
                clearable
              >
                <el-option
                  v-for="(val, i) in userSource"
                  :key="i"
                  :label="val"
                  :value="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="servicerId" label="客服">
              <el-select
                style="width:220px"
                v-model="searchCriteria.servicerId"
                filterable
                clearable
              >
                <el-option
                  v-for="(val, i) in userSource"
                  :key="i"
                  :label="val"
                  :value="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="filterCurrency" label="币种">
              <el-select
                style="width:220px"
                v-model="searchCriteria.filterCurrency"
                filterable
                clearable
              >
                <el-option
                  v-for="(v, i) in filterCurrencyMap"
                  :key="i"
                  :label="v"
                  :value="i"
                ></el-option
              ></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="waybillNos" label="单号">
              <el-input
                type="textarea"
                v-model="searchCriteria.waybillNos"
                :rows="2"
                clearable
              />
            </el-form-item>
            <el-form-item prop="referenceNos" label="参考号">
              <el-input
                type="textarea"
                v-model="searchCriteria.referenceNos"
                :rows="2"
                clearable
              />
            </el-form-item>
            <el-form-item prop="masterNumbers" label="M单号">
              <el-input
                type="textarea"
                v-model="searchCriteria.masterNumbers"
                :rows="2"
                clearable
              />
            </el-form-item>
            <el-form-item prop="trackNumbers" label="追踪号">
              <el-input
                type="textarea"
                v-model="searchCriteria.trackNumbers"
                :rows="2"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="accountTypeId" label="财务类型">
              <el-select
                style="width:220px"
                v-model="searchCriteria.accountTypeId"
                disabled
              >
                <el-option
                  v-for="(v, i) in accountTypeIdMap"
                  :key="i"
                  :label="m(v)"
                  :value="parseInt(i)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="bankAccountId" label="银行账号">
              <el-select
                style="width:220px"
                v-model="searchCriteria.bankAccountId"
                filterable
                clearable
              >
                <el-option
                  v-for="(v, i) in bankAccountIdMap"
                  :key="i"
                  :label="bankAccountIdMap[i]"
                  :value="parseInt(i)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="amount" label="金额">
              <el-input
                style="width:220px"
                v-model="searchCriteria.amount"
                placeholder="金额"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="targetCurrency" label="币种">
              <el-select
                style="width:220px"
                v-model="searchCriteria.targetCurrency"
                filterable
                clearable
                @change="targetCurrencyChange"
              >
                <el-option
                  v-for="(v, i) in targetCurrencyMap"
                  :key="i"
                  :label="v"
                  :value="v"
                ></el-option
              ></el-select>
            </el-form-item>
            <div class="margin-bottom flex justify-start">
              <span class="my_color" @click="selectRate">汇率： </span>
              <div class="my_left">
                <p
                  id="offAccountCurrencyRate"
                  class="margin-bottom-sm"
                  v-for="(v, i) in offAccountCurrencyRate"
                  :key="i"
                >
                  {{ offAccountCurrencyRate[i] }}
                </p>
              </div>
            </div>
            <el-form-item label="总计：">
              <div class="text-sm" v-show="isShow">
                <p class="text-bold">{{ totalOffResult }}</p>
                <p class="margin-0" v-show="totalWriteOffTitle">
                  销账总计：
                </p>
                <p class="margin-0" v-for="(v, i) in offCurrencyMap" :key="i">
                  {{ i }} ：{{ offCurrencyMap[i] }}
                </p>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 销账汇率 -->
    <el-dialog title="请选择销账汇率" :visible.sync="dialogTableVisible">
      <div style="height:550px;" class="scrollbar">
        <el-scrollbar style="height:100%">
          <el-table :data="writeoffData" ref="accountTable" class="text-sm">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              prop="sourceCurrency"
              label="原始转换币种"
            ></el-table-column>
            <el-table-column
              prop="targetCurrency"
              label="目标转换币种"
            ></el-table-column>
            <el-table-column prop="rate" label="转换币率">
              <template slot-scope="scope">
                <div @dblclick="showInput">
                  <span v-if="showRate">{{ scope.row.rate }}</span>
                  <el-input
                    v-if="showInputRate"
                    size="mini"
                    clearable
                    v-model="scope.row.rate"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="运算符">
              <template slot-scope="scope">
                <span v-if="scope.row.operator == 1">乘</span>
                <span v-if="scope.row.operator == 2">除</span>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="saveRate" size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-card>
      <div class="flex" style="float:left;">
        <el-checkbox-group v-model="selectedCustomerSons" size="small">
          <el-checkbox
            v-for="(item, key) in customerSon"
            :key="key"
            :label="key"
            border
            @change="chooseQuery(key)"
          >
            {{ item }}
          </el-checkbox>
        </el-checkbox-group>
      </div>

      <div class="flex justify-end margin-top">
        <el-button-group>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="search"
            v-if="showSearch"
            :loading="searchLoading"
            >搜索</el-button
          >
          <!--financeAccount.id == null ? true : false-->
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            v-if="showFilterFinanceDetails"
            @click="search"
            :loading="btnLoading"
            >查询(下面列表数据)</el-button
          >
          <el-button type="primary" size="mini" @click="amountTotal"
            >总计</el-button
          >
          <el-button type="primary" size="mini" @click="exportTable"
            >导出</el-button
          >
        </el-button-group>
      </div>
    </el-card>
    <!-- 表格区域 -->
    <el-card class="margin-top">
      <el-table size="mini" :data="tableData" class="text-sm" id="out-eltable">
        <el-table-column type="index" label="序号" width="40" />
        <ex-table-column
          prop="serCusId"
          label="客户"
          show-overflow-tooltip
          :auto-fit="true"
          :fit-header="true"
          v-if="showCus"
        >
          <template slot-scope="scope">
            {{ customerSon[scope.row.serCusId] }}
          </template>
        </ex-table-column>
        <el-table-column
          label="运单号"
          prop="waybillNo"
          sortable
        ></el-table-column>
        <el-table-column label="参考号" prop="referenceNo"></el-table-column>
        <el-table-column
          label="M单号"
          prop="masterNumber"
          sortable
        ></el-table-column>
        <el-table-column
          label="入库日期"
          prop="inStockTime"
          show-overflow-tooltip
          sortable
        ></el-table-column>
        <!--销售-->
        <el-table-column label="销售" prop="sales">
          <template slot-scope="scope">
            {{ userSource[scope.row["sales"]] }}
          </template>
        </el-table-column>
        <el-table-column label="客服" prop="servicerId">
          <template slot-scope="scope">
            {{ userSource[scope.row["servicerId"]] }}
          </template>
        </el-table-column>
        <!--费用名称-->
        <el-table-column label="费用名称" prop="costNameId" sortable>
          <template slot-scope="scope">
            {{ costNamesMap[scope.row["costNameId"]] }}
          </template>
        </el-table-column>
        <el-table-column label="余额" prop="remain"></el-table-column>
        <el-table-column
          label="币种"
          prop="currency"
          sortable
        ></el-table-column>

        <el-table-column prop="offMoney">
          <template slot="header" slot-scope="scope">
            <span>{{ writeOffAmountTitle }}</span>
            <span class="my_color" @click="selectAll">{{
              texts ? "全选" : "全不选"
            }}</span>
          </template>
          <template slot-scope="scope">
            <el-input
              size="mini"
              v-model="scope.row.offMoney"
              @focus="onFocus($event, scope)"
              @blur="onBlur"
              style="width:120px"
              clearable
            ></el-input>
            <span v-show="false">{{ scope.row.offMoney }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="利息"
          prop="interest"
          min-width="50"
        ></el-table-column>
        <el-table-column
          label="费用日期"
          prop="accountDate"
          sortable
        ></el-table-column>
        <el-table-column
          label="备注信息"
          prop="remark"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
    </el-card>

    <!--  新增费用搜索弹出窗  -->
    <el-dialog
      title="应收或应付明细"
      :visible.sync="receiveItemDialogVisible"
      width="80%"
      @close="clearData"
    >
      <!--开票申请信息-->
      <el-table
        ref="multipleTable"
        :data="receiveDetailTableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="运单号" prop="waybillNo"></el-table-column>
        <el-table-column label="参考号" prop="referenceNo"></el-table-column>
        <el-table-column
          label="M单号"
          prop="masterNumber"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="入库日期"
          prop="inStockTime"
          show-overflow-tooltip
        ></el-table-column>
        <!--销售-->
        <el-table-column label="销售" prop="sales">
          <template slot-scope="scope">
            {{ userSource[scope.row["sales"]] }}
          </template>
        </el-table-column>
        <el-table-column label="客服" prop="servicerId">
          <template slot-scope="scope">
            {{ userSource[scope.row["servicerId"]] }}
          </template>
        </el-table-column>
        <!--费用名称-->
        <el-table-column label="费用名称" prop="costNameId">
          <template slot-scope="scope">
            {{ costNamesMap[scope.row["costNameId"]] }}
          </template>
        </el-table-column>
        <el-table-column label="余额" prop="remain"></el-table-column>
        <el-table-column label="币种" prop="currency"></el-table-column>
        <el-table-column
          label="利息"
          prop="interest"
          min-width="50"
        ></el-table-column>
        <el-table-column
          label="费用日期"
          prop="accountDate"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="备注信息"
          prop="remark"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-button @click="toggleSelection()">取消选择</el-button>
        <el-button @click="insertDetail">OK</el-button>
      </div>
      <!--      {{this.multipleSelection}}-->
    </el-dialog>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import { clone } from "@/utils/clone";
import { parseTime } from "@/utils";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";

export default {
  data() {
    return {
      customerSon: {},
      selectedCustomerSons: [],
      customerSonReceiveDetailsMap: new Map(),
      customerType: "",
      receiveDetailTableData: [],
      multipleSelection: [],
      receiveItemDialogVisible: false,
      loading: false,
      showRate: true,
      showInputRate: false,
      pageLoading: false,
      btnLoading: false,
      searchLoading: false,
      isShow: false,
      mqCount: 0,
      timer: "",
      offMoney: "",
      accountNo: "",
      serCusId: "",
      accountNoVisible: false,
      // 是否显示搜索按钮
      showSearch: false,
      // 是否显示查询按钮
      showFilterFinanceDetails: false,
      // 销账总计文字显示
      totalWriteOffTitle: false,
      dialogTableVisible: false,
      totalOffResult: "",
      texts: true,
      searchCriteria: {
        accountTime: "",
        targetCurrency: "RMB",
        accountNo: "",
        serCusId: "",
        amount: "",
        remark: "",
        publicOpen: "1",
        bankAccountId: "",
        accountTypeId: "",
        filterCurrency: "",
        receivePaymentReamrk: "",
        inStockDate: []
      },
      rules: {
        serCusId: [
          { required: true, message: "请输入公司简称", trigger: "change" }
        ],
        amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
        currency: [
          { required: true, message: "请选择币种", trigger: "change" }
        ],
        bankAccountId: [
          { required: true, message: "请输入银行账号", trigger: "change" }
        ],
        accountTypeId: [
          { required: true, message: "请选择财务类型", trigger: "change" }
        ]
      },
      // 表格数据
      tableData: [],
      initTableData: [], //表格初始数据
      writeoffData: [], // 记账汇率
      offAccountCurrencyRate: [], //
      serCusIdMap: [],
      selectData: [], //选中汇率的数据
      remarkMap: [],
      offCurrencyMap: {},
      costNamesMap: [],
      bankAccountIdMap: [],
      accountTypeIdMap: {},
      filterCurrencyMap: [],
      targetCurrencyMap: [],
      userSource: [],
      financeAccount: null,
      editCustomerOrServiceMap: {},
      writeOffAmountTitle: "销账金额",
      customerBillIdStrs: "", //客户账单ID,
      checkCurrencyResult: true,
      intrestMap: {},
      showCus: false
    };
  },
  created() {
    let url = window.location.href;
    let arr = url.split("#");
    if (
      arr[0] === "http://www.tofba.com:8084/" ||
      arr[0] === "http://192.168.180.66/"
    ) {
      this.showCus = true;
    }
  },
  mounted() {
    if (this.$route.query.bankStatementAmount) {
      this.searchCriteria.amount = this.$route.query.bankStatementAmount;
    }
    this.searchCriteria.accountTime = parseTime(new Date(), "{y}-{m}-{d}");
    this.pageLoading = true;
    if (this.$route.query.customerBillIdStrs !== undefined) {
      this.showFilterFinanceDetails = true;
    }
    if (this.$route.query.pid === undefined) {
      this.showFilterFinanceDetails = true;
      this.showSearch = false;
    } else {
      this.showSearch = true;
      // 水单信息不为空,搜索按钮隐藏
      if (this.$route.query.customerBillIdStrs !== undefined) {
        this.showSearch = false;
      }
    }
    this.edit();

    // 检测数据是否在同步
    this.getMqCount();
    this.timer = setInterval(() => {
      this.getMqCount();
    }, 3000);
  },
  beforeDestory() {
    clearInterval(this.timer);
  },
  methods: {
    getMqCount() {
      let queues = [
        "YGBOOST-DATABASE-SYNC10",
        "YGBOOST-DATABASE-SYNC11",
        "YGBOOST-DATABASE-SYNC12",
        "YGBOOST-DATABASE-SYNC13",
        "YGBOOST-DATABASE-SYNC14",
        "YGBOOST-DATABASE-SYNC15",
        "YGBOOST-DATABASE-SYNC16",
        "YGBOOST-DATABASE-SYNC17",
        "YGBOOST-DATABASE-SYNC18",
        "YGBOOST-DATABASE-SYNC19"
      ];
      axios
        .get(
          constant.API_SERVER +
            "/open/getMqCount?queues=" +
            JSON.stringify(queues)
        )
        .then(
          response => {
            if (200 == response.status) {
              this.mqCount = response.data;
              if (0 == this.mqCount) {
                clearInterval(this.timer);
              }
            }
          },
          response => {}
        );
    },
    m(k) {
      return m(k);
    },
    // 显示输入框
    showInput() {
      this.showRate = false;
      this.showInputRate = true;
    },
    //  带入销账明细进界面中
    insertDetail() {
      if (this.multipleSelection.length === 0) {
        this.$message.info("请先勾选数据");
        return;
      }
      //将没有重复的应收明细数据添加进tableData中
      // debugger
      let tableDataDetailIds = this.tableData.map(data => {
        return data["waybillReceivePayablesId"];
      });
      this.multipleSelection.forEach(detail => {
        if (
          tableDataDetailIds.indexOf(detail["waybillReceivePayablesId"]) === -1
        ) {
          this.tableData.push(detail);
        }
      });
      //全选,自动调用计算总计方法
      this.selectAll();
      this.amountTotal();
      //清楚数据关闭弹窗
      // console.log(this.multipleSelection.valueOf());
      this.$refs.multipleTable.clearSelection();
      this.receiveItemDialogVisible = false;
    },
    //  多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //  关闭弹窗清除选项
    clearData() {
      this.$refs.multipleTable.clearSelection();
    },
    // 失去焦点事件
    onBlur() {
      // 调用计算利息
      console.log("失去焦点计算利息");
      this.calculatedInterest();
    },
    //获取焦点选中文字
    onFocus(event, scope) {
      this.$set(scope.row, "offMoney", scope.row.remain);
      event.target.select();
    },
    // 全选全不选
    selectAll() {
      this.$nextTick(() => {
        this.texts = !this.texts;
      });
      // 全选this.texts = false
      // 全不选 this.texts = true
      if (this.texts) {
        var data = this.tableData;
        if (!(data && data.length > 0)) {
          return;
        }
        data.forEach(item => {
          item["offMoney"] = item["remain"];
        });
        this.calculatedInterest();
      } else {
        var data = this.tableData;
        if (!(data && data.length > 0)) {
          return;
        }
        data.forEach(item => {
          item["offMoney"] = "";
        });
        this.cancleCalculatedInterest();
      }
    },
    // 编辑
    async edit() {
      console.log("~~~~~~~~~~~~~~~~~~~~~~~~~开始执行edit方法");
      /*请求示例开始 */
      this.loading = true;
      const data = {};
      let pid = this.$route.query.pid;
      if (pid) {
        data["id"] = pid;
      }
      /*客户销账跳转过来*/
      let customerBillIdStrs = this.$route.query.customerBillIdStrs;
      let currencyCode = this.$route.query.currencyCode;
      if (customerBillIdStrs) {
        data["customerBillIdStrs"] = customerBillIdStrs;
      }
      if (currencyCode) {
        data["currency"] = currencyCode;
      }
      console.log("~~~~~~~~~~~~~~~~~~~~~~~~~edit 请求参数");
      console.log(data);
      /*请求示例结束 */
      let res = await ajax("edit", data);
      console.log("~~~~~~~~~~~~~~~~~~~~~~~~~edit 响应结果");
      console.log(res);
      if (res.error) {
        this.$message.error(res.error);
        this.loading = false;
        return;
      }
      this.loading = false;
      // 费用名称
      this.costNamesMap = res.configPayNameSource;
      // 用户信息
      this.userSource = res.userSource;
      // 银行账户信息
      this.bankAccountIdMap = res.companyBankSource;
      // 财务类型
      this.accountTypeIdMap = res.receiveOrPaySource;
      // 搜索区域币种
      this.filterCurrencyMap = res.currencySource;
      // 记账币种
      this.targetCurrencyMap = res.currencySource;
      this.searchCriteria.accountNo = res.accountNo;
      // 记账时间
      if (res.financeAccount) {
        this.searchCriteria.accountTime = res.financeAccount.accountTime;
      }
      if (res.financeAccount.publicOpen != 1) {
        this.searchCriteria.publicOpen = "0";
      }
      this.accountNo = res.accountNo;
      // 编辑记账信息
      var entry = res.financeAccount;
      console.log("entry", entry);
      if (entry !== null && entry !== undefined) {
        this.isShow = true;
        this.totalWriteOffTitle = true;
        this.financeAccount = entry;
        // 记账金额
        this.searchCriteria.amount = entry.amount;

        // 记账币种
        this.searchCriteria.targetCurrency = entry.currency;
        // 银行账户
        var bankAccountId = entry.bankAccountId;
        if (bankAccountId) {
          this.searchCriteria.bankAccountId = entry.bankAccountId;
        }
        // 编辑渲染客户或者服务商
        if (res.editCustomerOrServiceMap) {
          this.editCustomerOrServiceMap = res.editCustomerOrServiceMap;
        }
        if (entry.serOrCusId) {
          for (let i in this.editCustomerOrServiceMap) {
            this.searchCriteria.serCusId = i;
          }
        }
        // 客户服务商Id
        if (entry.serOrCusId) {
          this.serCusId = entry.serOrCusId;
        }
        // 记账信息
        if (res.currencyList) {
          this.offAccountCurrencyRate = res.currencyList;
        }
        // 费用详情数据
        this.tableData = res.financeReceiveDetails;
        this.initTableData = res.financeReceiveDetails;
        // 总计
        this.totalOffResult = res.totalOffResult;
        // 按照币种分类
        this.offCurrencyMap = res.offCurrencyMap;
        // 记账类型
        this.searchCriteria.accountTypeId = entry.accountTypeId;
        if (res.rateData && res.rateData.length > 0) {
          this.writeoffData = JSON.parse(res.rateData);
        }
        this.searchCriteria.remark = entry.remark;
        this.calculatedInterest();
        this.orginalculatedInterest();
        //保留第一次原始利息信息
      } else {
        this.pageLoading = false;
      }
    },
    //客户或者服务商远程搜索事件
    async autoComplete(query) {
      if (query !== "" && query.length > 1) {
        let res = await ajax("autoComplete", {
          query: query
        });
        this.serCusIdMap = res;
        // console.log(res);
      }
    },
    // 选择客户或者服务商
    selectCustomerOrService() {
      let serCusId = this.searchCriteria.serCusId;
      if (serCusId && serCusId.indexOf("_") > -1) {
        this.searchCriteria.accountTypeId = 1;
      } else {
        this.searchCriteria.accountTypeId = 0;
      }
    },
    // 应收应付备注
    async queryReceiveReamrk(query) {
      if (query !== "" && query.length > 1) {
        let accountType = null;
        if (this.searchCriteria.accountTypeId == "应收") {
          accountType = 0;
        } else {
          accountType = 1;
        }
        let res = await ajax("queryReceiveReamrk", {
          accountType: accountType,
          remark: query
        });
        console.log(res);
        this.remarkMap = res;
      }
    },
    // 总计
    async amountTotal() {
      // 调用计算利息
      this.calculatedInterest();
      let currency = this.searchCriteria.targetCurrency;
      if (!currency) {
        this.$message.error("请先选择目标币种");
        return;
      }
      var offAccountCurrencyRate = this.offAccountCurrencyRate;
      this.checkCurrency(currency);
      var checkResult = this.checkCurrencyResult;
      if (!checkResult && offAccountCurrencyRate.length == 0) {
        this.$message.error("请先选择汇率");
        return false;
      }
      var offMap = {};
      var data = this.tableData;
      if (!(data && data.length > 0)) {
        return;
      }
      data.forEach(item => {
        var _currency = item["currency"];
        var offMoney = item["offMoney"];
        if (
          _currency &&
          offMoney !== null &&
          offMoney !== "" &&
          offMoney !== undefined &&
          !isNaN(Number(offMoney))
        ) {
          var has = _currency in offMap;
          if (has) {
            var exsitVal = offMap[_currency];
            var res = Number(exsitVal) + Number(offMoney);
            res = Math.round(res * 100) / 100;
            offMap[_currency] = res;
          } else {
            offMap[_currency] = Number(offMoney);
          }
        }
      });
      // 获取汇率区域信息
      /* 请求示例**/
      /*
      var data = {};
      data["currency"] = "EUR";
      data["rateData"] = "";
      data["offMap"] = '{"EUR":12.43}';*/
      let res = await ajax("total", {
        currency: this.searchCriteria.targetCurrency,
        rateData: JSON.stringify(this.writeoffData),
        offMap: JSON.stringify(offMap)
      });
      console.log(res);
      if (res.success == true) {
        // 总计渲染
        this.totalOffResult = res.totalOffResult;
        this.isShow = true;
        this.totalWriteOffTitle = true;
        // 渲染销账总计下面各个币种
        this.offCurrencyMap = offMap;
        // 记账金额
        this.searchCriteria.amount = res.totalDataNum;
      } else {
        this.$message.error(res.message);
      }
    },
    // 点击汇率发送请求
    async selectRate() {
      let targetCurrency = this.searchCriteria.targetCurrency;
      if (!targetCurrency) {
        this.$message.error("请选择记账币种!");
        return;
      }
      let res = await ajax("selectOffAccountCurrencyRate", {
        targetCurrency: this.searchCriteria.targetCurrency
      });
      console.log(res);
      this.writeoffData = res.offAccountCurrencyRates;
      if (
        this.searchCriteria.targetCurrency !== null &&
        this.searchCriteria.targetCurrency !== ""
      ) {
        this.dialogTableVisible = true;
      } else {
        this.$message.error("请先选择原始转换币种!");
      }
    },
    // 汇率选择保存事件
    async saveRate() {
      this.selectData = this.$refs.accountTable.selection;
      if (
        this.selectData === null &&
        this.selectData === undefined &&
        this.selectData.length === 0
      ) {
        this.$message.error("请选择记账汇率!");
        return;
      }
      let array = new Array();
      let checkArray = new Array();
      let sourceCurrencyArray = new Array();
      let flag = false;
      for (var i = 0; i < this.selectData.length; i++) {
        let selectedRow = this.selectData[i];
        let sourceCurrency = selectedRow.sourceCurrency;
        let targetCurrency = selectedRow.targetCurrency;
        let rate = selectedRow.rate;
        let operator = selectedRow.operator;
        let checkPa = sourceCurrency + targetCurrency;
        if (checkArray.includes(checkPa)) {
          flag = true;
          return false;
        } else {
          checkArray.push(checkPa);
        }
        array.push({
          sourceCurrency: sourceCurrency,
          targetCurrency: targetCurrency,
          rate: rate,
          operator: operator
        });
        if (!sourceCurrencyArray.includes(sourceCurrency)) {
          sourceCurrencyArray.push(sourceCurrency);
        }
      }
      // if (flag) {
      //   this.$message.error("不允许选择同样的币种转换!");
      //   return;
      // }
      if (array.length == 0) {
        this.$message.error("请先选择销账汇率");
        return;
      }
      let selectTargetCurrency = this.searchCriteria.targetCurrency;
      let offCurrencyArray = new Array();
      if (this.tableData !== null && this.tableData.length > 0) {
        this.tableData.forEach(item => {
          let offMoney = item.offMoney;
          let currency = item.currency;
          if (
            offMoney &&
            !isNaN(Number(offMoney)) &&
            currency &&
            currency != selectTargetCurrency &&
            !offCurrencyArray.includes(currency)
          ) {
            offCurrencyArray.push(currency);
          }
        });
        offCurrencyArray.forEach(item => {
          if (!sourceCurrencyArray.includes(item)) {
            flag = true;
            return false;
          }
        });
        if (flag) {
          this.$message.error("请先选择要销账币种的销账汇率", "", 1000);
          return;
        }
      }
      console.log(array);

      let res = await ajax("saveSelectOffAccountCurrencyRate", {
        data: JSON.stringify(array)
      });
      this.writeoffData = this.selectData;
      console.log(res);
      if (res.success == true) {
        this.offAccountCurrencyRate = res.result;
        this.dialogTableVisible = false;
      } else {
        this.$message.error("请先选择销账汇率！");
      }
    },
    // 查询事件
    async search() {
      if (this.$route.query.pid || this.$route.query.customerBillIdStrs) {
        this.filterTableData();
      } else {
        this.loading = true;
        if (this.$route.query.pid !== undefined) {
          this.receiveItemDialogVisible = true;
        }
        let data = {};
        //region 查询条件
        // 运单查询条件
        const waybillNos = this.searchCriteria.waybillNos;
        if (waybillNos) {
          data["waybillNos"] = waybillNos.split("\n"); // 换行符分割，List
        }
        const referenceNos = this.searchCriteria.referenceNos;
        if (referenceNos) {
          data["referenceNos"] = referenceNos.split("\n"); // 换行符分割，List
        }
        const masterNumbers = this.searchCriteria.masterNumbers;
        if (masterNumbers) {
          data["masterNumbers"] = masterNumbers.split("\n"); // 换行符分割，List
        }
        const trackNumbers = this.searchCriteria.trackNumbers;
        if (trackNumbers) {
          data["trackNumbers"] = trackNumbers.split("\n"); // 换行符分割，List
        }
        const saleId = this.searchCriteria.saleId;
        if (saleId) {
          data["saleId"] = saleId; // 销售
        }
        const servicerId = this.searchCriteria.servicerId;
        if (servicerId) {
          data["servicerId"] = servicerId; //客服
        }
        // 费用查询条件
        const serCusId = this.searchCriteria.serCusId; // 客户或者服务商
        if (serCusId) {
          data["serCusId"] = serCusId;
        }
        const costNames = this.searchCriteria.costNames; // 费用名称
        if (costNames) {
          data["costNames"] = costNames;
        }
        const filterCurrency = this.searchCriteria.filterCurrency; // 费用币种
        if (filterCurrency) {
          data["filterCurrency"] = filterCurrency;
        }
        const inputUser = this.searchCriteria.inputUser; // 录入人
        if (inputUser) {
          data["inputUser"] = inputUser;
        }
        const receivePaymentReamrk = this.searchCriteria.receivePaymentReamrk; // 应收应付备注
        if (receivePaymentReamrk) {
          data["receivePaymentReamrk"] = receivePaymentReamrk;
        }
        const accountDate = this.searchCriteria.accountDate;
        if (accountDate && accountDate.length === 2) {
          const startAccountTime = accountDate[0]; //费用开始时间
          if (startAccountTime) {
            data["startAccountTime"] = startAccountTime;
          }
          const endAccountTime = accountDate[1]; //费用结束时间
          if (endAccountTime) {
            data["endAccountTime"] = endAccountTime;
          }
        }
        //  入库时间条件搜索
        const inStockDate = this.searchCriteria.inStockDate;
        if (inStockDate && inStockDate.length === 2) {
          const startInStockDate = inStockDate[0]; //费用开始时间
          if (startInStockDate) {
            data["startInStockTime"] = startInStockDate;
          }
          const endInStockTime = inStockDate[1]; //费用结束时间
          if (endInStockTime) {
            data["endInStockTime"] = endInStockTime;
          }
        }
        //endregion
        console.log(data);
        this.serCusId = data.serCusId;
        this.offAccountCurrencyRate = [];
        this.totalOffResult = "";
        data["relatedSon"] = this.searchCriteria.relatedSon;
        let res = await ajax("query", data);
        console.log(res);
        if (this.$route.query.pid === undefined) {
          this.tableData = res.tableData;
          //子公司销账明细
          this.customerSonReceiveDetailsMap = new Map();
          this.customerSonReceiveDetailsMap.set(this.serCusId, this.tableData);
          this.selectedCustomerSons = [];
          this.selectedCustomerSons.push(this.serCusId);
        } else {
          this.receiveDetailTableData = res.tableData;
        }
        this.customerSon = res.customerSon;
        this.userSource = res.userSource;
        this.costNamesMap = res.costNamesMap;
        this.loading = false;
      }
    },

    chooseQuery(serCusId) {
      if (this.selectedCustomerSons.indexOf(serCusId) > -1) {
        this.queryCustomerSonFinanceReceiveDetails(serCusId);
      } else {
        this.removeCustomerSonFinanceReceiveDetails(serCusId);
      }
    },

    /**
     * 查询子公司销账明细数据
     * */
    async queryCustomerSonFinanceReceiveDetails(serCusId) {
      this.loading = true;
      if (this.$route.query.pid !== undefined) {
        this.receiveItemDialogVisible = true;
      }
      let customerItemReceiveDetails = this.customerSonReceiveDetailsMap.get(
        serCusId
      );
      if (customerItemReceiveDetails !== undefined) {
        this.tableData = this.tableData.concat(customerItemReceiveDetails);
        this.loading = false;
        return;
      }
      let param = {};
      if (serCusId) {
        // 客户或者服务商
        param["serCusId"] = serCusId;
      }
      let res = await ajax("queryCustomerSonFinanceReceiveDetails", param);
      if (this.$route.query.pid === undefined) {
        this.customerSonReceiveDetailsMap.set(serCusId, res.tableData);
        this.tableData = this.tableData.concat(res.tableData);
      } else {
        this.receiveDetailTableData = res.tableData;
      }
      this.loading = false;
    },

    /**
     * 移除子公司销账明细数据
     * */
    removeCustomerSonFinanceReceiveDetails(serCusId) {
      let tableData = this.tableData;
      for (let i = 0; i < tableData.length; i++) {
        if (tableData[i].serCusId.toString() === serCusId) {
          tableData.splice(i--, 1);
        }
      }
      this.tableData = tableData;
    },

    // 页面过滤查询事件
    filterTableData() {
      this.btnLoading = true;
      this.tableData = [];
      const tableData = clone(this.initTableData);
      console.log("tableData :>> ", tableData);
      // 运单查询条件
      const data = {};
      const waybillNos = this.searchCriteria.waybillNos;
      if (waybillNos) {
        data["waybillNos"] = waybillNos.split("\n"); // 换行符分割，List
      }
      const referenceNos = this.searchCriteria.referenceNos;
      if (referenceNos) {
        data["referenceNos"] = referenceNos.split("\n"); // 换行符分割，List
      }
      const masterNumbers = this.searchCriteria.masterNumbers;
      if (masterNumbers) {
        data["masterNumbers"] = masterNumbers.split("\n"); // 换行符分割，List
      }
      const trackNumbers = this.searchCriteria.trackNumbers;
      if (trackNumbers) {
        data["trackNumbers"] = trackNumbers.split("\n"); // 换行符分割，List
      }
      if (this.searchCriteria.receivePaymentReamrk) {
        data.receivePaymentReamrk = this.searchCriteria.receivePaymentReamrk;
      }
      if (this.searchCriteria.saleId) {
        data.saleId = this.searchCriteria.saleId;
      }
      if (this.searchCriteria.accountDate) {
        data.accountDate = this.searchCriteria.accountDate;
      }
      if (this.searchCriteria.filterCurrency) {
        data.filterCurrency = this.searchCriteria.filterCurrency;
      }
      if (this.searchCriteria.costNames.length > 0) {
        data.costNames = this.searchCriteria.costNames;
      }
      console.log("data :>> ", data);
      let arrLength = Object.keys(data);
      if (arrLength.length === 0) {
        this.tableData = tableData;
      }
      const l = tableData.length;
      for (var i = 0; i < l; i++) {
        // 运单号
        if (
          data.waybillNos &&
          tableData[i] &&
          data.waybillNos.some(f => f === tableData[i].waybillNo)
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
          // i--; // 如果不减，将漏掉一个元素
        }
        // 参考号
        if (
          data.referenceNos &&
          tableData[i] &&
          data.referenceNos.some(f => f === tableData[i].referenceNo)
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // masterNumbers
        if (
          data.masterNumbers &&
          tableData[i] &&
          data.masterNumbers.some(f => f === tableData[i].masterNumber)
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // trackNumbers
        if (
          data.trackNumbers &&
          tableData[i] &&
          data.trackNumbers.some(f => f === tableData[i].trackNumber)
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // remark
        if (
          data.receivePaymentReamrk &&
          tableData[i] &&
          tableData[i].remark &&
          data.receivePaymentReamrk.indexOf(tableData[i].remark) !== -1
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // saleId
        if (
          data.saleId &&
          tableData[i] &&
          tableData[i].saleId &&
          tableData[i].saleId == data.saleId
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // filterCurrency
        if (
          data.filterCurrency &&
          tableData[i] &&
          tableData[i].currency &&
          tableData[i].currency == data.filterCurrency
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // costNames

        if (data.costNames && tableData[i]) {
          // console.log("tableData[i] :>> ", tableData[i]);
          // this.tableData.push(tableData[i]);
        }
        if (
          data.costNames &&
          tableData[i] &&
          tableData[i].costNameId &&
          tableData[i].costNameId === parseInt(data.costNames)
        ) {
          this.tableData.push(tableData[i]);
          // tableData.splice(i, 1);
          // i--;
        }
        // accountDate
        if (data.accountDate && tableData[i]) {
          const s = new Date(data.accountDate[0]).getTime();
          const t = new Date(tableData[i].accountDate).getTime();
          const e = new Date(data.accountDate[1]).getTime();
          if (s <= t <= e) {
            this.tableData.push(tableData[i]);
            // tableData.splice(i, 1);
            // i--;
          }
        }
      }
      // this.tableData = tableData;
      // console.log("tableData :>> ", tableData);
      this.btnLoading = false;
    },
    // 保存事件
    async save() {
      var checkResult = this.checkFinanceAccountParams();
      if (!checkResult) {
        return;
      }
      this.amountTotal();
      const data = {};
      if (this.financeAccount !== null && this.financeAccount.id != null) {
        data["id"] = this.financeAccount.id; // 编辑传递ID
      }
      data["accountNo"] = this.searchCriteria.accountNo; // 记账编号 TODO
      data["accountTime"] = this.searchCriteria.accountTime; // 记账时间
      data["serCusId"] = this.serCusId; // 客户或者服务商ID
      data["accountTypeId"] = this.searchCriteria.accountTypeId; // 记账类型
      data["currency"] = this.searchCriteria.targetCurrency; // 记账币种
      data["bankAccountId"] = this.searchCriteria.bankAccountId; // 银行
      data["amount"] = this.searchCriteria.amount; // 记账金额
      if (this.searchCriteria.remark) {
        data["remark"] = this.searchCriteria.remark; // 记账备注
      }
      if (this.selectData.length > 0) {
        data["rateData"] = this.selectData; // 记账汇率JSON字符串
      }
      data["publicOpen"] = this.searchCriteria.publicOpen;
      console.log("选中汇率的数据", this.selectData);
      var offList = [];
      var table_data = this.tableData;
      if (table_data && table_data.length > 0) {
        for (const item of table_data) {
          let _currency = item["currency"];
          let offMoney = item["offMoney"];
          let remain = item["remain"];
          if (
            remain &&
            offMoney &&
            !isNaN(Number(offMoney)) &&
            !isNaN(Number(remain))
          ) {
            if (Math.abs(offMoney) > Math.abs(remain)) {
              this.$message.error(
                "销账金额：" + offMoney + "大于余额：" + remain
              );
              return;
            }
          }
          if (
            _currency &&
            offMoney !== null &&
            offMoney !== "" &&
            offMoney !== undefined &&
            !isNaN(Number(offMoney))
          ) {
            var obj = {};
            obj["receivableId"] = item["waybillReceivePayablesId"];
            obj["isAbroad"] = item["isAbroad"];
            obj["receiveCurrency"] = _currency;
            obj["offCurrency"] = offMoney;
            obj["waybillId"] = item["waybillId"];
            // 取得利息
            if (item["interest"]) {
              obj["interest"] = item["interest"];
            }
            obj["accountDate"] = item["accountDate"];
            offList.push(obj);
          }
        }
      }
      if (offList.length > 0) {
        data["offList"] = offList; // 记账应收应付JSON字符串
      }
      if (
        this.$route.query.customerBillIdStrs &&
        this.$route.query.customerBillIdStrs !== undefined &&
        this.$route.query.customerBillIdStrs !== ""
      ) {
        data["customerBillIdStrs"] = this.$route.query.customerBillIdStrs; // 销售账单ID
      }
      //return;
      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "account_save_" + new Date().getTime()
      };
      data["intrestMap"] = this.intrestMap;
      this.loading = true;
      let res = await ajax("save", data, attrs);
      this.getMqCount();

      let success = res.success;
      if (!success) {
        this.$message.error(res.message);
        this.loading = false;
        return;
      } else if (data["offList"].length > 50) {
        this.$message.warning("保存成功,数据量过大,请等待五分钟后再操作");
      } else {
        this.$message.success("保存成功");
        this.loading = false;
      }
      let financeAccountNo = res.financeAccountNo;
      if (financeAccountNo !== "" && financeAccountNo !== undefined) {
        window.open(
          "#/blank/finance__voucher__copy?financeAccountNo=" + financeAccountNo
        );
      }

      setTimeout(() => {
        location.reload();
      }, 3000);
    },
    // 计算利息 利率*费用
    calculatedInterest() {
      var data = this.tableData;
      if (!(data && data.length > 0)) {
        console.log("table数据为空");
        return;
      }
      data.forEach(item => {
        var offMoney = item["offMoney"];
        console.log("利率:" + item["interestRate"]);
        if (offMoney && !isNaN(offMoney)) {
          var interestRate = item["interestRate"];
          if (interestRate) {
            var interest = Math.round(interestRate * offMoney * 1000) / 1000;
            console.log("利息:" + interest);
            // item["interest"] = interest;
            this.$set(item, "interest", interest);
          }
        } else {
          // item["interest"] = "";
          this.$set(item, "interest", "");
        }
        // console.log("利息:" + interest);
      });
      this.pageLoading = false;
    },
    // 计算利息 利率*费用
    orginalculatedInterest() {
      var data = this.tableData;
      if (!(data && data.length > 0)) {
        console.log("table数据为空");
        return;
      }
      data.forEach(item => {
        var offMoney = item["offMoney"];
        console.log("利率:" + item["interestRate"]);
        if (offMoney && !isNaN(offMoney)) {
          var interestRate = item["interestRate"];
          if (interestRate) {
            var interest = Math.round(interestRate * offMoney * 1000) / 1000;
            console.log("利息:" + interest);
            // item["interest"] = interest;
            this.$set(item, "interest", interest);
            this.intrestMap[item.waybillReceivePayablesId] = interest;
            console.log(interest);
            console.log(item.waybillReceivePayablesId);
          }
        } else {
          // item["interest"] = "";
          this.$set(item, "interest", "");
          this.intrestMap[item.waybillReceivePayablesId] = "";
        }
        // console.log("利息:" + interest);
      });
      console.log("this.intrestMap" + this.intrestMap);
      this.pageLoading = false;
    },
    cancleCalculatedInterest() {
      var data = this.tableData;
      if (!(data && data.length > 0)) {
        return;
      }
      data.forEach(item => {
        // 利息清空，利润不变
        item["interest"] = "";
      });
    },
    // 清空利息
    cancleInterest() {
      var data = this.tableData;
      if (!(data && data.length > 0)) {
        return;
      }
      data.forEach(item => {
        // 利息清空，利润不变
        item["interestRate"] = "";
      });
    },
    // 保存参数校验
    checkFinanceAccountParams() {
      var accountTime = this.searchCriteria.accountTime;
      var serCusId = this.searchCriteria.serCusId;
      var accountTypeId = this.searchCriteria.accountTypeId;
      var currency = this.searchCriteria.targetCurrency;
      var bankAccountId = this.searchCriteria.bankAccountId;
      var amount = this.searchCriteria.amount;
      if (!accountTime) {
        this.$message.error("记账时间为空");
        return false;
      }
      if (!serCusId) {
        this.$message.error("公司简称为空");
        return false;
      }
      if (accountTypeId === null) {
        this.$message.error("财务类型为空");
        return false;
      }
      if (!currency) {
        this.$message.error("币种为空");
        return false;
      }
      if (!bankAccountId) {
        this.$message.error("银行账号为空");
        return false;
      }
      if (amount === "" || amount === null) {
        this.$message.error("记账金额为空");
        return false;
      }
      if (isNaN(Number(amount))) {
        this.$message.error("记账金额不合法");
        return false;
      }
      // if (!this.isShow) {
      //   this.$message.error("请先点击总计");
      //   return false;
      // }
      return true;
    },
    // 校验币种,总计按钮时调用
    checkCurrency(tmp) {
      var flag = true;
      var data = this.tableData;
      if (!(data && data.length > 0)) {
        this.checkCurrencyResult = true;
        return;
      }
      // data.forEach(item => {
      //   let offMoney = item["offMoney"];
      //   let currency = item["currency"];
      //   if (offMoney && currency != tmp) {
      //     this.checkCurrencyResult = false;
      //     return;
      //   }
      // });
      // return;
    },
    // TODO 客户欠款明细跳转过来查询事件,根据查询条件直接过滤tableData数据,无需请求后台
    filterFinanceReceiveDetails() {},
    // TODO 点击销账金额文本框事件,用余额赋值给文本框,且选中文本框内容,触发重新计算利息事件
    // TODO 币种变化事件，(汇率上方币种)。汇率和总计内容情况
    // TODO 记账币种选择事件,需要清除汇率和总计，重新计算
    targetCurrencyChange() {
      this.offAccountCurrencyRate = [];
      this.totalOffResult = "";
      this.offCurrencyMap = {};
      this.totalWriteOffTitle = false;
    },
    // 记账日期变化事件
    accountTimeChange() {
      this.afreshCalInterestRate();
    },
    // 记账日期发生变更事件
    async afreshCalInterestRate() {
      // 无记账关联费用信息
      var table_data = this.tableData;
      console.log(1);
      if (!(table_data && table_data.length > 0)) {
        return;
      }
      let serCusId = this.searchCriteria.serCusId; // 客户ID
      let accountTypeId = this.searchCriteria.accountTypeId; // 只用应收才计算
      let accountTime = this.searchCriteria.accountTime;

      console.log(
        "serCusId:" +
          serCusId +
          ",accountTypeId:" +
          accountTypeId +
          ",accountTime:" +
          accountTime
      );
      if (accountTypeId !== 0) {
        return;
      }
      if (serCusId && accountTypeId !== null && accountTime) {
        console.log(2);
        // 清空利息
        this.cancleInterest();
        var waybillReceivePayablesIds = new Array();
        var abroadWaybillReceivePayablesIds = new Array();
        table_data.forEach(item => {
          var waybillReceivePayablesId = item["waybillReceivePayablesId"];
          var isAbroad = item["isAbroad"];
          if (isAbroad == 0) {
            waybillReceivePayablesIds.push(waybillReceivePayablesId);
          } else {
            abroadWaybillReceivePayablesIds.push(waybillReceivePayablesId);
          }
        });
        var params = {};
        params["waybillReceivePayablesIds"] = null; // 海空运运单费用ID
        params["abroadWaybillReceivePayablesIds"] = null; // 海外仓费用ID
        params["serCusId"] = serCusId; // 客户ID
        params["type"] = accountTypeId; // 只用应收才计算
        params["accountDate"] = accountTime;
        if (waybillReceivePayablesIds.length > 0) {
          params["waybillReceivePayablesIds"] = waybillReceivePayablesIds;
        }
        if (abroadWaybillReceivePayablesIds.length > 0) {
          params[
            "abroadWaybillReceivePayablesIds"
          ] = abroadWaybillReceivePayablesIds;
        }
        console.log(params);
        let res = await ajax("afreshCalInterestRate", params);
        console.log(res);

        var abroadWaybillMap = res.abroadWaybillMap;
        var waybillMap = res.waybillMap;
        table_data.forEach(item => {
          var waybillReceivePayablesId = item["waybillReceivePayablesId"];
          var isAbroad = item["isAbroad"];
          if (isAbroad == 0) {
            if (waybillMap) {
              var has = waybillReceivePayablesId in waybillMap;
              if (has) {
                var interestRate = waybillMap[waybillReceivePayablesId];
                // item["interestRate"] = interestRate;
                this.$set(item, "interestRate", interestRate);
              }
            }
          } else {
            if (abroadWaybillMap) {
              var has = waybillReceivePayablesId in abroadWaybillMap;
              if (has) {
                var interestRate = abroadWaybillMap[waybillReceivePayablesId];
                // item["interestRate"] = interestRate;
                this.$set(item, "interestRate", interestRate);
              }
            }
          }
        });
        this.calculatedInterest();
      }
    },
    // 保存修改 accountNo
    async saveAccountNo() {
      let newAccountNo = this.accountNo;
      if (newAccountNo === "") {
        this.$message.error("记账编号不能为空");
        return;
      }
      if (
        !(Number.isInteger(Number(newAccountNo)) && Number(newAccountNo) > 0)
      ) {
        this.$message.error("必须是大于0的数字");
        return;
      }
      let oldAccountNo = this.searchCriteria.accountNo;
      if (parseInt(oldAccountNo) < parseInt(newAccountNo)) {
        this.$message.error("不允许录入最大记账编号+1的数");
        return;
      }
      let pid = this.$route.query.pid;
      let data = {};
      data["accountNo"] = newAccountNo;
      if (pid !== undefined) {
        data["id"] = this.pid;
      }
      console.log(
        "pid:" + pid + ",new:" + newAccountNo + ",old:" + oldAccountNo
      );
      console.log(data);
      let res = await ajax("checkAccountNo", data);
      console.log(res);
      // 存在
      if (res.success) {
        this.$message.error("记账编号已经存在!");
        return;
      }
      this.searchCriteria.accountNo = newAccountNo;
      this.accountNoVisible = false;
    },
    closePop() {
      this.accountNoVisible = false;
      this.accountNo = this.searchCriteria.accountNo;
    },
    // 导出
    exportTable() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-eltable"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "销账明细.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  }
};
</script>
<style scoped>
.size_full {
  width: 100%;
}
.my_color {
  color: #ff7575;
  cursor: pointer;
}
.my_left {
  margin-left: 54px;
}
.el-scrollbar {
  display: flex;
  justify-content: space-around;
  margin-right: -15px;
}
div >>> .el-scrollbar__wrap {
  overflow-x: hidden;
  width: 110%;
  height: 100%;
}
</style>
